package com.margo.project.web.servlet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/asyn", asyncSupported = true)
public class MargoAsynServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("主线程开始");
		System.out.println(Thread.currentThread().getName()+" 主线程开始..........");
		AsyncContext startAsyn=request.startAsync();
		startAsyn.start(new Runnable() {
			
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName()+" 异步线程开始..........");
				sayName();
				startAsyn.complete();
				AsyncContext asyncContext=request.getAsyncContext();
				ServletResponse asynResponse=asyncContext.getResponse();
				try {
					asynResponse.getWriter().write("异步线程测试");
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+" 异步线程结束..........");
			}
		});
		System.out.println(Thread.currentThread().getName()+" 主线程结束..........");
	}
	
	public void sayName() {
		System.out.println(Thread.currentThread().getName()+" processing..........");
		System.out.println("name is margo");
	}

}
